package cap.dao.impl;

import cap.bean.ChatRoomVo;
import cap.dao.ChatRoomDao;
import cap.db.DBPool;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class ChatRoomDaoImpl implements ChatRoomDao {
    Connection conn=null;
    PreparedStatement ps=null;
    ResultSet rs=null;
    ChatRoomVo chatRoomVo=new ChatRoomVo();
    @Override
    public void setChartroomVo(ChatRoomVo chatRoomVo) throws SQLException {
        conn=DBPool.getConn();
        String sql = "insert into chatterroom(roomname,roomhost,roomnumber,content,roomonline) values(?,?,?,?,0)";
        Integer that = 0;
        ps = conn.prepareStatement(sql);
        ps.setString(1,chatRoomVo.getRoomname());
        ps.setString(2,chatRoomVo.getRoomhost());
        ps.setInt(3,chatRoomVo.getRoomnumber());
        ps.setString(4,chatRoomVo.getContent());
        that = ps.executeUpdate();
        DBPool.close(null,ps,conn);
    }
    @Override
    public List<ChatRoomVo> getChatRoomVo() throws SQLException {
        conn=DBPool.getConn();
        String sql = "select * from chatterroom";
        List<ChatRoomVo> res = new ArrayList<ChatRoomVo>();
        ps = conn.prepareStatement(sql);
        rs = ps.executeQuery();
        int i =0;
        while(rs.next()){
            ChatRoomVo it = new ChatRoomVo();
            it.setRoomnumber(rs.getInt("roomnumber"));
            it.setRoomname(rs.getString("roomname"));
            it.setContent(rs.getString("content"));
            it.setRoomhost(rs.getString("roomhost"));
            it.setRoomonline(rs.getInt("roomonline"));
            res.add(it);
            i++;
        }
        DBPool.close(rs,ps,conn);
        return res;
    }

    @Override
    public int getchatroomnumbers() throws SQLException {
        conn=DBPool.getConn();
        String sql = "select count(*) number from chatterroom";
        Integer that = 0;
        ps = conn.prepareStatement(sql);
        rs = ps.executeQuery();
        while (rs.next()) {
            that = rs.getInt("number");
        }
        DBPool.close(rs,ps,conn);
        return that;
    }

    @Override
    public Integer[] getroomnumber(String room) throws SQLException {
        conn=DBPool.getConn();
        String sql = "select roomonline,roomnumber from chatterroom where id=?";
        Integer[] numbers = new Integer[2];
        Integer number = 0;
        Integer online = 0;
        ps = conn.prepareStatement(sql);
        ps.setString(1,room);
        rs = ps.executeQuery();
        while ((rs.next())){
            numbers[0] = rs.getInt("roomnumber");
            numbers[1] = rs.getInt("roomonline");
        }
        DBPool.close(rs,ps,conn);
        return numbers;
    }
}
